import Taro from "@tarojs/taro"
import { getToken, clearUser } from "./index"

const requestUrl = "https://weplaysports.com.cn"
//const requestUrl = "https://weplaysports.com.cn"
//const requestUrl = "https://charsmagic.cloud"
// const requestUrl = "http://42.51.8.56:9080"

const onResponseComplete = (httpData: any, resolve: Function, reject: Function, url: String) => {
  /* http状态码为200开始 */
  if (httpData.statusCode === 200) {
    resolve(httpData.data)
    /* 判断http状态码为401,403等特殊情况 */
  } else if (httpData.statusCode === 401 || httpData.statusCode === 403) {
    /* 其他情况 */
    Taro.showToast({
      title: "登录失效",
      icon: "none",
    })
    clearUser()
    setTimeout(() => {
      Taro.switchTab({
        url: "/pages/mine/index",
      })
    }, 1500)
    reject({})
  } else {
    Taro.showToast({
      title: "未知的错误请求",
      icon: "none",
    })
    reject({})
  }
}

const interceptor = function (chain) {
  const Authorization = getToken()
  const requestParams = chain.requestParams
  const header = {
    ...requestParams.header,
  }
  if (Authorization) {
    header["Authorization"] = Authorization
  }
  requestParams.header = header
  return chain.proceed(requestParams).then((res: any) => {
    return res
  })
}

Taro.addInterceptor(interceptor)

function get(url, params = {}): Promise<any> {
  return new Promise((resolve, reject) => {
    console.log("post url&data", url, params)
    Taro.request({
      url: `${requestUrl}${url}`,
      method: "GET",
      data: params,
      complete(httpData: any) {
        onResponseComplete(httpData, resolve, reject, url)
      },
    })
  })
}

function post(url, data = {}): Promise<any> {
  return new Promise((resolve, reject) => {
    console.log("post url&data", url, data)

    const u = `${requestUrl}${url}`
    Taro.request({
      url: u,
      method: "POST",
      data,
      complete(httpData: any) {
        onResponseComplete(httpData, resolve, reject, url)
      },
    })
  })
}

export default {
  get,
  post,
}
